package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


/**
 * @author 杰哥不要啦~
 * @date 2021/11/3
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //探花喜欢  保存或更新
    @Override
    public Boolean saveOrUpdate(Long userid, Long likeUserId, boolean isLike) {
        try {
        //1、查询数据
        Query query = Query.query(Criteria.where("userId").is(userid).and("likeUserId").is(likeUserId));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        //2、如果不存在，保存
        if(userLike == null) {
            userLike = new UserLike();
            userLike.setUserId(userid);
            userLike.setLikeUserId(likeUserId);
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUpdated(System.currentTimeMillis());
            userLike.setIsLike(isLike);
            mongoTemplate.save(userLike);
        }else {
            //3、更新
            Update update = Update.update("isLike", isLike)
                    .set("updated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,UserLike.class);
        }
        return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
